
<!--
  * @FileDescription: 代码编辑器
  * @Author: 刘轩毓
  * @Date: 2023.6.25
-->
<template>
  <div class="editor">
    <div class="editor" ref="editorWrapper"></div>
  </div>
</template>

<script setup lang="ts" name="ace">
import Ace from 'ace-builds';
import 'ace-builds/src-noconflict/ace.js';
import 'ace-builds/src-noconflict/mode-python';
import 'ace-builds/src-noconflict/mode-mysql';
import 'ace-builds/src-noconflict/theme-chrome';
import 'ace-builds/src-noconflict/theme-twilight';
import 'ace-builds/src-noconflict/ext-language_tools.js';
import 'ace-builds/src-min-noconflict/ext-language_tools'; // 启用自动代码提示
import 'ace-builds/src-min-noconflict/ext-beautify'; // 启用美化插件
import 'ace-builds/src-min-noconflict/snippets/python'; // Python代码段

import { ref, onMounted, watch, onBeforeUnmount } from 'vue';

const props = defineProps({
  modelValue: {
    type: String,
    default: {},
  },
  readOnly: {
    type: Boolean,
    default: false
  },
  showLine: {
    type: Boolean,
    default: true
  },
  language: {
    type: String,
    default: 'python'
  },
});

const editor = ref();
const editorWrapper = ref();

const emits = defineEmits(['update:modelValue', 'editorInit'])

const addSome = (val: String) => {
  editor.value.insert(val);
  editor.value.gotoLine(editor.value.getCursorPosition().row + 1, editor.value.getCursorPosition().column - 1);
};

const addFormula = (val: String) => {
  editor.value.insert(val);
  editor.value.gotoLine(editor.value.getCursorPosition().row + 1, editor.value.getCursorPosition().column);
};

const editorInit = () => {
  editor.value = Ace.edit(editorWrapper.value);
  editor.value.session.setMode(`ace/mode/${props.language}`);
  Ace.config.set('basePath', 'node_modules/ace-builds/src-noconflict');
  editor.value.setTheme("ace/theme/twilight");
  editor.value.setValue(props.modelValue);
  editor.value.setOptions({
    fontSize:16,
    enableSnippets: true,
    enableLiveAutocompletion: true,
    enableBasicAutocompletion: true,
    readOnly: props.readOnly,
    showLineNumbers: props.showLine,
    showGutter: props.showLine,
  });
  editor.value.on('change', () => {
    const value = editor.value.getValue();
    emits('update:modelValue', value);
    
  })
  emits('editorInit', editor.value)
}
onBeforeUnmount(() => {
  editor.value.commands.removeCommand('custom-command');
});

watch(() => props.modelValue, (val) => {
  const currentPosition = editor.value.getCursorPosition();
  editor.value.setValue(val);
  editor.value.clearSelection();
  editor.value.moveCursorToPosition(currentPosition);
  editor.value.renderer.$cursorLayer.restartTimer()
  // editor.value.execCommand("startAutocomplete");//重新激活  
});

onMounted(() => {
  editorInit()
});


defineExpose({ addSome,addFormula });
</script>

<style scoped lang="scss">
.editor {
  height: 100%;
}

.ace_layer{
 .ace_gutter-cell {
    display: block !important;
  }
}


</style>